﻿/**************************************************************
 *
 * 命名空间：Sgr.UPMS.Application.Commands.Menus
 * 创建时间：2025/3/20
 * 描述：修改菜单命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Menus;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Menus
{
    /// <summary>
    /// 修改菜单命令处理器
    /// </summary>
    public class UpdateMenuCommandHandler : IRequestHandler<UpdateMenuCommand, CommandResult<bool>>
    {
        private readonly IMenuManage _menuManage;
        private readonly IMenuRepository _menuRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdateMenuCommandHandler(
            IMenuManage menuManage,
            IMenuRepository menuRepository)
        {
            _menuManage = menuManage;
            _menuRepository = menuRepository;
        }

        /// <summary>
        /// 处理命令
        /// </summary>
        public async Task<CommandResult<bool>> Handle(UpdateMenuCommand command, CancellationToken cancellationToken)
        {
            // 获取要修改的菜单
            var menu = await _menuRepository.GetAsync(command.Id, cancellationToken);
            if (menu == null)
                return CommandResult.NotFound<bool>("未找到指定的菜单");

            // 如果需要更新名称或者更新父Id，则需要验证更新后的名称是否唯一
            if (command.Name != menu.Name || (command.ParentId.HasValue && command.ParentId.Value > 0 && menu.ParentId != command.ParentId.Value))
            {
                // 验证同级菜单名称唯一性
                var nameExists = await _menuManage.ValidateNameUniquenessAsync(
                    command.Name,
                    command.ParentId ?? menu.ParentId,
                    menu.Id,
                    cancellationToken);

                if (!nameExists.IsComply)
                    return CommandResult.Invalid<bool>(nameExists.Message);
            }

            //如果路由名称不为空，则验证路由名称唯一性
            if (!string.IsNullOrEmpty(command.RouteName))
            {
                var routeNameExists = await _menuManage.ValidateRouteNameUniquenessAsync(command.RouteName, menu.Id, cancellationToken);
                if (!routeNameExists.IsComply)
                    return CommandResult.Invalid<bool>(routeNameExists.Message);
            }

            // 更新基本信息
            menu.UpdateBasicInfo(
                command.Name,
                command.Icon,
                command.RouteName,
                command.RoutePath,
                command.ComponentPath,
                command.RedirectPath,
                command.Permission,
                command.Description,
                command.Order);

            // 更新配置信息
            menu.UpdateConfig(
                command.ExternalLink,
                command.Hidden,
                command.KeepAlive,
                command.Affix,
                command.Target);

            //更新菜单父Id
            if (command.ParentId.HasValue && command.ParentId.Value > 0 && menu.ParentId != command.ParentId.Value)
            {
                var moveResult = await _menuManage.MoveNodeAsync(menu, command.ParentId.Value, 5, cancellationToken);
                if (!moveResult.IsComply)
                    return CommandResult.Invalid<bool>($"更新上级菜单失败,{moveResult.Message}");
            }

            // 如果禁用
            if (command.IsActive != menu.IsActive)
            {
                if (command.IsActive)
                    await _menuManage.ActivateAsync(menu, cancellationToken);
                else
                    await _menuManage.DeactivateAsync(menu, cancellationToken);
            }

            // 保存修改
            await _menuRepository.UpdateAsync(menu, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "菜单更新成功");
        }
    }
}